package com.xuecheng.media.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.xuecheng.base.exception.XuChengException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.media.mapper.MediaFilesMapper;
import com.xuecheng.media.model.dto.QueryMediaParamsDto;
import com.xuecheng.media.model.dto.UploadFileParamsDto;
import com.xuecheng.media.model.dto.UploadFileResultDto;
import com.xuecheng.media.model.po.MediaFiles;
import com.xuecheng.media.model.po.MediaProcess;
import com.xuecheng.media.service.MediaFileService;
import com.xuecheng.media.service.MediaProcessService;
import io.minio.*;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Mr.M
 * @version 1.0
 * @description 媒资管理服务
 * @date 2022/9/10 8:58
 */
@Service
@Slf4j
public class MediaFileServiceImpl extends ServiceImpl<MediaFilesMapper,MediaFiles> implements MediaFileService {

    @Autowired
    private MediaFilesMapper mediaFilesMapper;

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket.files:mediafiles}")
    private String bucketFiles;

    @Value("${minio.bucket.videofiles:video}")
    private String bucketVideo;

    @Autowired
    private MediaFileService mediaFileServiceProxy;

    @Autowired
    private MediaProcessService mediaProcessService;
    @Override
    public PageResult<MediaFiles> queryMediaFiels(Long companyId, PageParams pageParams, QueryMediaParamsDto queryMediaParamsDto) {

        //构建查询条件对象
        LambdaQueryWrapper<MediaFiles> queryWrapper = new LambdaQueryWrapper<>();

        //分页对象
        Page<MediaFiles> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<MediaFiles> pageResult = mediaFilesMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<MediaFiles> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<MediaFiles> mediaListResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return mediaListResult;

    }

    /**
     * 获取合并后的文件路径
     *
     * @param fileMd5 文件md5值
     * @return 合并后文件路径
     */
    private static String getMergeFilePath(String fileMd5) {
        String substring = fileMd5.substring(0, 2);
        String filePath = StrUtil.join(StrUtil.SLASH, substring.charAt(0), substring.charAt(1), fileMd5) + StrUtil.SLASH;
        return filePath;
    }

    @Override
    public UploadFileResultDto uploadFile(Long companyId, UploadFileParamsDto uploadFileParamsDto, String localFilePath) {
        // 文件名称
        String filename = uploadFileParamsDto.getFilename();
        // 获取文件后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        // 获取mineType
        String mimeType = getMimeType(suffix);
        String defaultFolderPath = getDefaultFolderPath();
        String fileMd5 = SecureUtil.md5(new File(localFilePath));
        // 上传对象名称
        String objName = defaultFolderPath + fileMd5 + suffix;
        // 上传文件到minio
        boolean isUpload = uploadMinio(localFilePath, objName, mimeType, bucketFiles);
        if (!isUpload) {
            XuChengException.cast("文件上传失败");
        }
        // 保存数据到数据库
        MediaFiles mediaFiles = mediaFileServiceProxy.saveMediaFiles(companyId, uploadFileParamsDto, filename, fileMd5, objName, bucketFiles);
        // 响应前端数据
        UploadFileResultDto uploadFileResultDto = new UploadFileResultDto();
        BeanUtil.copyProperties(mediaFiles, uploadFileResultDto);
        return uploadFileResultDto;
    }

    @Override
    @Transactional
    public MediaFiles saveMediaFiles(Long companyId, UploadFileParamsDto uploadFileParamsDto, String filename, String fileMd5, String objName, String bucketName) {
        // 根据id查询媒资信息
        MediaFiles selectById = mediaFilesMapper.selectById(fileMd5);
        // 保存媒资信息
        if (ObjectUtil.isEmpty(selectById)) {
            MediaFiles mediaFiles = new MediaFiles();
            mediaFiles.setId(fileMd5);
            BeanUtil.copyProperties(uploadFileParamsDto, mediaFiles);
            mediaFiles.setBucket(bucketName);
            mediaFiles.setAuditStatus("002003");
            mediaFiles.setCompanyId(companyId);
            mediaFiles.setFilename(filename);
            mediaFiles.setFileType("001001");
            mediaFiles.setStatus("1");
            mediaFiles.setFileId(fileMd5);
            mediaFiles.setCreateDate(LocalDateTime.now());
            mediaFiles.setChangeDate(LocalDateTime.now());
            mediaFiles.setUrl(StrUtil.SLASH + bucketName + StrUtil.SLASH + objName);
            mediaFiles.setFilePath(objName);
            int insert = mediaFilesMapper.insert(mediaFiles);
            if (insert <= 0) {
                log.error("插入媒资信息{},失败", mediaFiles);
                XuChengException.cast("添加媒资信息失败");
            }
            // 添加媒资信息到待处理任务
            addWaitingTask(filename, mediaFiles);
            return mediaFiles;
        }
        return selectById;
    }

    /**
     * 保存媒资信息到媒资未处理表种
     * @param filename 文件名称
     * @param mediaFiles 媒资实体
     */
    private void addWaitingTask(String filename, MediaFiles mediaFiles) {
        // 获取文件后缀
        String suffix = StrUtil.DOT+ FileUtil.getSuffix(filename);
        // 获取文件媒体类型
        String mimeType = getMimeType(suffix);

        // 如果是avi视频添加到视频待处理表
        if (mimeType.equals("video/x-msvideo")){
            MediaProcess mediaProcess =  BeanUtil.copyProperties(mediaFiles, MediaProcess.class);
            mediaProcess.setCreateDate(LocalDateTime.now());
            // 设置失败次数
            mediaProcess.setFailCount(0);
            // 设置未处理数
            mediaProcess.setStatus("1");
            mediaProcessService.save(mediaProcess);
        }
    }

    @Override
    public RestResponse<Boolean> checkFiles(String fileMd5) {
        // 查询数据看是否存在上传文件信息
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileMd5);
        if (ObjectUtil.isNotEmpty(mediaFiles)) {
            // 获取文件存储的minio信息
            String filePath = mediaFiles.getFilePath();
            String bucket = mediaFiles.getBucket();
            // minio查询文件信息
            GetObjectResponse minioObject = null;
            try {
                minioObject = minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(filePath).build());
                if (ObjectUtil.isNotEmpty(minioObject)) {
                    return RestResponse.success(true);
                }
            } catch (Exception e) {
                log.error("minio查询文件：{},异常", filePath);
            } finally {
                // 流的关闭
                IoUtil.close(minioObject);
            }
        }
        return RestResponse.success(false);
    }

    @Override
    public RestResponse<Boolean> checkChunk(String fileMd5, Integer chunk) {
        // 获取分块文件上传路径
        String filePath = getChunkFilePath(fileMd5);
        GetObjectResponse object = null;
        try {
            // 查询分块信息
            object = minioClient.getObject(GetObjectArgs.builder().bucket(bucketVideo)
                    .object(filePath + chunk).build());
            // 不存在则返回true
            if (ObjectUtil.isNotEmpty(object)) {
                return RestResponse.success(true);
            }
        } catch (Exception e) {
            // 出现异常也得走false
            log.error("minio查询分块文件:{},不存在", filePath + chunk);
        } finally {
            IoUtil.close(object);
        }
        // 否则返回false
        return RestResponse.success(false);
    }

    @Override
    public RestResponse uploadChunk(String localPath, String fileMd5, Integer chunk) {
        // 获取上传文件路径
        String chunkFilePath = getChunkFilePath(fileMd5);
        // 获取上传文件类型
        File temFile = new File(localPath);
        String mimeType = getMimeType(temFile.getName().substring(temFile.getName().lastIndexOf(".")));
        ObjectWriteResponse objectWriteResponse = null;
        try {
            objectWriteResponse = minioClient.uploadObject(UploadObjectArgs.builder().bucket(bucketVideo).filename(localPath)
                    .object(chunkFilePath + chunk).contentType(mimeType).build());
            if (ObjectUtil.isNotEmpty(objectWriteResponse)) {
                return RestResponse.success(true, "分块文件" + chunk + "上传成功");
            }
        } catch (Exception e) {
            log.error("minio上传文件:{},分块:{}，失败", fileMd5, chunk);
            XuChengException.cast(e.getMessage());
        }
        return RestResponse.validfail(false, "分块" + chunk + "文件上传失败");
    }

    @Override
    public RestResponse mergeChunks(Long companyId,String fileMd5, String fileName, Integer chunkTotal, UploadFileParamsDto uploadFileParamsDto) {
        // 获取分块路径
        String chunkFilePath = getChunkFilePath(fileMd5);
        // 合并文件路径
        String mergeFilePath = getMergeFilePath(fileMd5);
        // 获取文件扩展名
        String suffix = FileUtil.getSuffix(fileName);
        String mergeName = mergeFilePath + fileMd5 + StrUtil.DOT + suffix;
        // 合并分块文件
        List<ComposeSource> composeSources = Stream.iterate(0, i -> ++i).limit(chunkTotal)
                .map(i -> ComposeSource.builder().bucket(bucketVideo).object(chunkFilePath + i).build())
                .sorted(Comparator.comparing(ObjectArgs::object)).collect(Collectors.toList());
        ComposeObjectArgs composeObjectArgs = ComposeObjectArgs.builder().bucket(bucketVideo)
                .object(mergeName).sources(composeSources).build();
        try {
            minioClient.composeObject(composeObjectArgs);
        } catch (Exception e) {
            log.error("文件合并：bucket:{},mergeName:{},失败", bucketVideo, mergeName);
            XuChengException.cast("文件合并失败");
        }
        // 文件校验
        Boolean checkMergeFile = checkMergeFile(fileMd5, mergeName,uploadFileParamsDto);
        if (!checkMergeFile) {
            return RestResponse.validfail("文件校验失败");
        }
        // 保存信息入库
        mediaFileServiceProxy.saveMediaFiles(companyId, uploadFileParamsDto, fileName, fileMd5, mergeName, bucketVideo);
        // 删除分块数据
        mediaFileServiceProxy.deleteChunk(chunkTotal, chunkFilePath);
        return RestResponse.success(true);
    }

    @Override
    @Transactional
    public void deleteChunk(Integer chunkTotal, String chunkFilePath) {
        // 删除分块文件
        List<DeleteObject> deleteObjects = Stream.iterate(0, i -> ++i).limit(chunkTotal)
                .map(i -> new DeleteObject(chunkFilePath + i)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder()
                .objects(deleteObjects).bucket(bucketVideo).build());
        // 一定要迭代输出结果，不然不生效，懒加载机制
        for (Result<DeleteError> result : results) {
            DeleteError error = null;
            try {
                error = result.get();
            } catch (Exception e) {
                log.error("Error in deleting object " + error.objectName() + "; " + error.message());
                XuChengException.cast("删除分块失败");
            }
        }
    }

    /**
     * 校验合并文件值
     * @param fileMd5 文件md5值
     * @param mergeName 合并文件名称(包含路径)
     * @return 是否校验成功
     */
    private Boolean checkMergeFile(String fileMd5, String mergeName,UploadFileParamsDto uploadFileParamsDto) {
        GetObjectArgs getObjectArgs = GetObjectArgs.builder().bucket(bucketVideo).object(mergeName).build();
        File tempFile = downLoadFile(fileMd5, mergeName, getObjectArgs);
        if (tempFile == null) return false;
        uploadFileParamsDto.setFileSize(tempFile.length());
        return true;
    }

    @Override
    public File downLoadFile(String fileMd5, String mergeName, GetObjectArgs getObjectArgs) {
        File tempFile = null;
        GetObjectResponse object = null;
        try {
            object = minioClient.getObject(getObjectArgs);
            tempFile = File.createTempFile("minio", ".temp");
            IoUtil.copy(object, new FileOutputStream(tempFile));
            if (!SecureUtil.md5(tempFile).equals(fileMd5)) {
                return null;
            }
        } catch (Exception e) {
            log.error("下载合并:{},失败", mergeName);
            XuChengException.cast("下载合并文件出错");
        } finally {
            IoUtil.close(object);
        }
        return tempFile;
    }

    /**
     * 根据md5值获取视频的分块存储路径
     *
     * @param fileMd5 上传文件md5值
     */
    private String getChunkFilePath(String fileMd5) {
        String substring = fileMd5.substring(0, 2);
        String filePath = StrUtil.join(StrUtil.SLASH, substring.charAt(0), substring.charAt(1), fileMd5, "chunk") + StrUtil.SLASH;
        return filePath;
    }

    /**
     * 设置默认上传路径
     *
     * @return
     */
    private String getDefaultFolderPath() {
        String today = DateUtil.today();
        String folder = today.replace(StrUtil.DASHED, StrUtil.SLASH) + StrUtil.SLASH;
        return folder;
    }

    /**
     * 上传文件到minio
     *
     * @param localFilePath 本地上传文件路径
     * @param objectName    对象名称
     * @param mimeType      媒体类型
     * @param bucket        存储桶
     * @return true 上传成功 false上传失败
     */
    @Override
    public boolean uploadMinio(String localFilePath, String objectName, String mimeType, String bucket) {
        // 新建上传参数
        try {
            UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder().
                    filename(localFilePath).bucket(bucket).object(objectName).contentType(mimeType).build();
            minioClient.uploadObject(uploadObjectArgs);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传文件出错,bucket:{},objectName:{},错误信息:{}", bucketFiles, objectName, e.getMessage());
        }
        return false;
    }

    /**
     * 删除Minio文件
     *
     * @param filePath 文件路径
     * @param bucket   文件桶
     * @return 是否删除成功
     */
    @Override
    public boolean deleteUploadFile(String filePath, String bucket) {
        List<DeleteObject> deleteObjects = Stream.iterate(0, i -> i++).limit(1)
                .map(t -> new DeleteObject(filePath)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucket)
                .objects(deleteObjects).build());
        // 一定要迭代输出结果，不然不生效，懒加载机制
        for (Result<DeleteError> result : results) {
            DeleteError error = null;
            try {
                error = result.get();
            } catch (Exception e) {
                log.error("Error in deleting object " + error.objectName() + "; " + error.message());
                XuChengException.cast("删除分块失败");
            }
        }
        return true;
    }

    private String getMimeType(String suffix) {
        if (suffix == null) {
            suffix = "";
        }
        ContentInfo mimeTypeMatch = ContentInfoUtil.findExtensionMatch(suffix);
        //通用mimeType，字节流
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        if (mimeTypeMatch != null) {
            mimeType = mimeTypeMatch.getMimeType();
        }
        return mimeType;
    }
}
